import 'package:bloc/bloc.dart';
import '../api/juejin_service.dart';
import '../models/personal_entity.dart';

enum LoadingStatus {
  loading,
  success,
  failed,
}

class PersonalResponse {
  PersonalEntity? personalProfile;
  LoadingStatus status = LoadingStatus.loading;

  PersonalResponse({this.personalProfile, required this.status});
}

abstract class PersonalEvent {}

class FetchEvent extends PersonalEvent {}

class FetchSucessEvent extends PersonalEvent {}

class FetchFailedEvent extends PersonalEvent {}

class PersonalBloc extends Bloc<PersonalEvent, PersonalResponse> {
  final String userId;
  PersonalEntity? _personalProfile;
  PersonalBloc(PersonalResponse initial, {required this.userId})
      : super(initial) {
    on<FetchEvent>((event, emit) {
      getPersonalProfile(userId);
    });
    on<FetchSucessEvent>((event, emit) {
      emit(PersonalResponse(
        personalProfile: _personalProfile,
        status: LoadingStatus.success,
      ));
    });
    on<FetchFailedEvent>((event, emit) {
      emit(PersonalResponse(
        personalProfile: null,
        status: LoadingStatus.failed,
      ));
    });
    add(FetchEvent());
  }

  void getPersonalProfile(String userId) async {
    _personalProfile = await JuejinService().getPersonalProfile(userId);
    if (_personalProfile != null) {
      add(FetchSucessEvent());
    } else {
      add(FetchFailedEvent());
    }
  }
}
